<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\jwt_token;
use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\WeekDay;
use app\api\model\v1\EnterUnit;
use app\api\model\v1\Facts;
use app\api\model\v1\Sms;
use app\api\model\v1\SystemConfig;
use app\api\model\v1\Users;
use app\BaseController;
use Qcloud\Sms\SmsMultiSender;
use think\facade\Cache;
use think\facade\Config;
use think\Request;

class Message extends BaseController
{
    use FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/9/6
     * @Time: 15:24
     * @return mixed
     * 获取token
     */
    public function access_token()
    {
        //配置appid
        $appid = Config::get('wechat.zfhf.app_id') ;
        //配置appscret
        $secret = Config::get('wechat.zfhf.app_secret');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        //获取access_token
        $access_token = $this->geturl($url)["access_token"];
        return $access_token;
    }

    public static function SendMsg($data, $access_token)
    {
        $MsgUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token; //微信官方接口，需要拼接access_token

        return json_decode(self::curl($MsgUrl, $params = json_encode($data), $ispost = 1, $https = 1)); //访问接口，返回参数
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/6
     * @Time: 14:44
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取开启订阅消息模版
     */
    public function getTemplateId(){
        $data = SystemConfig::where(['name'=>'template'])->find();
        if (is_null($data)){
            return $this->response(403,"该模版未找到");
        }
        return $this->response($data);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/6
     * @Time: 15:28
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 发送模版消息
     */
    public function sendTemplateMsg(){
        $data_arr = $this->request->param();
        $user = Users::find($data_arr['user_id']);
        if (is_null($user)){
            return $this->response(403,"未找到该用户");
        }
        $url_2 = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $this->access_token();
        $data = [];
        $data['template_id'] = $data_arr['template_id'];
        $data['page'] = "pages/index/index";
        if ($data_arr['type'] === 1){ //开启
            $data['touser'] = $user['openid'];
            $data['data'] = [
                "thing1" => [
                    'value' => '政风行风热线'
                ],
                "time2" => [
                    'value' => date('Y-m-d H:i:s', time())
                ],
                "thing3" => [
                    'value' => $user['nickname']
                ]
            ];
        }else if ($data_arr['type'] === 2){
            $unit = EnterUnit::find($data_arr['unit_id']);
            if (is_null($unit)){
                return $this->response(403,"找不到该单位");
            }
            $user = Users::where(['unit_id'=>$unit['id']])->find();
            $data['touser'] = $user['openid'];
            $data['data'] = [
                "thing1" => [
                    'value' => $data_arr['title']
                ],
                "thing2" => [
                    'value' => $this->filterSensitive($data_arr['content'])
                ],
                "time3" => [
                    'value' => date('Y-m-d H:i:s', time())
                ],
                "thing4" => [
                    'value' => $user['nickname']
                ]
            ];
        }
        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        $data['miniprogram_state'] = 'trial';
        $this->posturl($url_2, $data);
        return $this->response();
//        var_dump($this->posturl($url_2, $data));

    }



    public function test(){
        $url_2 = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $this->access_token();
        $data = [];
        $data['touser'] = "oORLt5cM_VuXZRKOP3hysGHI_5rs";
        $data['template_id'] = '9usq1hqxkEBenWpW3xrE7eA9YUV5NdbHYn4MxGgz4Ec';
        $data['page'] = "pages/index/index";
        $data['data'] = [
            "thing1" => [
                'value' => '你好'
            ],
            "thing2" => [
                'value' => '我是内容'
            ],
            "time3" => [
                'value' => date('Y-m-d H:i:s', time())
            ],
            "thing4" => [
                'value' => "我是名称"
            ]
        ];
        $data['miniprogram_state'] = 'trial';
        $this->posturl($url_2, $data);
    }

    public function geturl($url)
    {

        /** @var *
         * curl get请求封装,返回json数据格式数据
         */
        $headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }


    public function posturl($url, $data)
    {
        /** @var *
         * curl post请求封装,返回json数据格式数据
         */
        $data = json_encode($data);
        $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output, true);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/7
     * @Time: 10:01
     * @return \think\response\Json
     * 保存音频
     */
    public function SaveAudio(){
        $file=$this->request->file('file');
        if (!$file) {
            return $this->response(501, '请选择上传文件');
        }
        $result = $this->save($file, 'audio');
        return $this->response($result);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/7
     * @Time: 13:24
     * @return \think\response\Json
     * 获取类别总数
     */
    public function getFactCount(){
        $res = Facts::field('count(*) as count,fact_type')->group('fact_type')->select()->toArray();
        foreach ($res as $key=>$v){
            $res[$key]['fact_type_name'] = Facts::$fact_type[$v['fact_type']];
        }
        return $this->response($res);
    }

    /**
     * @param $mobile //需要通知的手机号
     * @param $type //当前类别
     * @param $data //内容
     * @User: 刘海龙
     * @Date: 2021/10/14  9:33
     * 2023-7-8 增加短信存储
     * @return mixed
     * 短信通知
     */
    public static function sendMessage($mobile,$handsetTailNumber='',$type,$data,$fact_id=0){
        $phoneNumbers = [$mobile];
        $AppId = Config::get('sms.AppId');
        $key = Config::get('sms.AppKey');
        if ($type === 1){
            $templateId = '1157124'; //通知
            $params = ['【'.$data.'】'];
        }else if ($type === 2){
            $templateId = '1157128'; //咨询模版
            $params = [$handsetTailNumber,'【'.$data.'】'];
        }else if ($type === 3){ //通知主持人
            $templateId = '1157133';
            $params = ['【'.$data.'】'];
        }else if ($type === 4){ //主持人转交成功通知
            $templateId = '1157136';
            $params = [];
        }else if($type === 5){//主持人退回问题
            $templateId = '1157829';
            $params = ['【'.$data.'】','请及时查看！'];
        }else if($type === 6){
            $templateId = '1843001';//案件逾期提醒
            $params = [$data];
        }else{
            $templateId = '';
            $params = [];
        }
        $smsSign = Config::get('sms.sign');
        $msender = new SmsMultiSender($AppId, $key);
//        $result=json_encode(['code'=>200]);
        $result = $msender->sendWithParam("86", $phoneNumbers, $templateId, $params, $smsSign, "", "");  // 签名参数不能为空串
        $rsp = json_decode($result, true);

        Sms::create([
            'tel'=>$mobile,
            'content'=>$data,
            'remark'=>$result,
            'fact_id'=>$fact_id,
            'type'=>$type,
        ]);
        return $rsp;
    }
}
